package com.itheima.advice;

import cn.hutool.json.JSONUtil;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

//public class RecordTimeAspect {
//    @Around("execution(* com.itheima.service.impl.*.*(..))")
//    public Object abc(ProceedingJoinPoint pjp) throws Throwable{
//        long begin = System.currentTimeMillis();
//        Object result =pjp.proceed();
//        long end = System.currentTimeMillis();
//        log.info("执行耗时" + (end -begin ));
//        return result;
//    }
//}
@Aspect
@Component
@Slf4j
public class RecordTimeAspect {
    @Autowired
    OperateLogMapper operateLogMapper;
//    @Around("execution (* com.itheima.controller..save(..)) ||" +"execution (* com.itheima.controller..del(..)) ||"
//    + "execution (* com.itheima.controller..update(..)) ")
@Around("@annotation(com.itheima.advice.LogOperation)")

    public Object abc(ProceedingJoinPoint pjp) throws Throwable{
    OperateLog operateLog = new OperateLog();
    System.out.println("当前操作者id是:" +CurrentHolder.getUserId());
        Integer operateEmpId = CurrentHolder.getUserId();
        long begin  = System.currentTimeMillis();
        LocalDateTime operateTime = LocalDateTime.now();
        Object returnV =  pjp.proceed();
        String returnValue =returnV.toString();
        String className = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().getName();
        Object[] methodParam = pjp.getArgs();
        String methodParams = JSONUtil.toJsonStr(methodParam);
        long end = System.currentTimeMillis();
        long costTime = end -begin;
    log.info("执行耗时:" + costTime );
    operateLogMapper.insert(new OperateLog(null,operateEmpId,operateTime, className, methodName, methodParams, returnValue, costTime));
//{operateEmpId}, #{operateTime}, #{className}, #{methodName}, #{methodParams}, #{returnValue}, #{costTime}
        return returnV;
    }
}
